/**
 * 
 */
package pq.util;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * @author tqthe
 * 
 */
public class AppConfigReader {

	private Document document;
	private HashMap<String, String> settings = new HashMap<String, String>();

	/**
	 * Load server config xml file
	 * 
	 * @param xmlFile
	 */
	public AppConfigReader(String xmlFile) {

		DocumentBuilder documentBuilder = null;
		DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
				.newInstance();

		try {
			documentBuilder = documentBuilderFactory.newDocumentBuilder();
			document = documentBuilder.parse(new File(xmlFile));
			document.normalize();

			// Map all key - value to hash map
			mapSettings();
		} catch (ParserConfigurationException ex) {
			ex.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Get value of specific key
	 * 
	 * @param key
	 *            - The key to get value
	 * @return Return corresponding value of input key. Return null if the key
	 *         does not exist.
	 */
	public String getValue(String key) {

		return settings.get(key);
	}

	/**
	 * Map all key - value to hash map
	 */
	private void mapSettings() {

		Element root = document.getDocumentElement();
		NodeList entries = root.getElementsByTagName("entry");
		String value = null;
		String key = null;

		for (int i = 0; i < entries.getLength(); i++) {

			Element entry = (Element) entries.item(i);
			key = entry.getAttribute("key");
			value = entry.getAttribute("value");

			settings.put(key, value);
		}
	}

}
